package com.jfreer.mybatis.expand.xmlmapper.elements;

import com.jfreer.mybatis.expand.IntrospectedTableMyBatis3Freework;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator;

/**
 * User: landy
 * Date: 14-6-28
 * Time: 下午8:31
 */
public class DeleteInBatchElementGenerator extends AbstractXmlElementGenerator {
    @Override
    public void addElements(XmlElement parentElement) {
        if (introspectedTable.getPrimaryKeyColumns().size() != 1) {
            /**
             * 当主键数量不为1时，不生成该方法。
             * a.没有主键
             * b.复合主键
             */
            return;
        }
        XmlElement answer = new XmlElement("delete"); //$NON-NLS-1$

        answer.addAttribute(new Attribute(
                "id", ((IntrospectedTableMyBatis3Freework) introspectedTable).getDeleteInBatchStatementId())); //$NON-NLS-1$

        context.getCommentGenerator().addComment(answer);

        StringBuilder sb = new StringBuilder();
        sb.append("delete from "); //$NON-NLS-1$
        sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());
        answer.addElement(new TextElement(sb.toString()));

        sb.setLength(0);
        sb.append("where "); //$NON-NLS-1$
        IntrospectedColumn pk = introspectedTable.getPrimaryKeyColumns().get(0);
        sb.append(MyBatis3FormattingUtilities
                .getEscapedColumnName(pk));
        sb.append(" in "); //$NON-NLS-1$
        answer.addElement(new TextElement(sb.toString()));
        XmlElement foreach = new XmlElement("foreach");
        foreach.addAttribute(new Attribute("collection","list"));
        foreach.addAttribute(new Attribute("item","item"));
        foreach.addAttribute(new Attribute("index","index"));
        foreach.addAttribute(new Attribute("separator",","));
        foreach.addAttribute(new Attribute("open","("));
        foreach.addAttribute(new Attribute("close",")"));
        foreach.addElement(new TextElement("#{item}"));
        answer.addElement(foreach);
        parentElement.addElement(answer);
    }
}
